<template>
  <div v-loading="loading">
    <div class="satisified-review">
      <!--  开关  -->
      <div class="satisified-review-item satisified-review-open">
        <div>
          <div class="title">{{ $t('projectManage.review.title1') }}</div>
          <div class="tip">{{ $t('projectManage.review.desc1') }}</div>
        </div>
        <el-switch v-model="autoReviewState" :active-value="true" :inactive-value="false" @change="updateReviewSetting"></el-switch>
      </div>

      <!--  回访对象设置  -->
      <div v-show="autoReviewState" class="satisified-review-item">
        <div class="title">{{ $t('projectManage.review.title2') }}</div>
        <div class="review-content">
          <el-radio-group class="satisified-review-item-type" v-model="reviewType" @input="updateReviewSetting">
            <el-radio label="customer">{{ $t('projectManage.review.desc2') }}</el-radio>
            <el-radio v-if="phoneFields.length" label="otherPhone" class="phone-field">{{ $t('projectManage.review.desc3') }}
              <el-select v-show="reviewType === 'otherPhone' " v-model="reviewPhoneFieldName" :placeholder="$t('projectManage.review.desc5')" @change="updateReviewSetting">
                <el-option
                  v-for="item in phoneFields"
                  :key="item.fieldName"
                  :label="item.displayName"
                  :value="item.fieldName">
                </el-option>
              </el-select>
            </el-radio>
          </el-radio-group>
        </div>
      </div>

      <!--  回访问卷设置  -->
      <div v-show="autoReviewState" class="satisified-review-item">
        <div class="title">{{ $t('projectManage.review.title3') }}</div>
        <div class="programme">
          <div>{{ $t('projectManage.review.desc4') }}</div>
          <el-select v-model="questionId" :placeholder="$t('common.base.pleaseSelect')" @change="updateReviewSetting">
            <el-option
              v-for="item in allQuestions"
              :key="item.satisfactionId"
              :label="item.satisfactionName"
              :value="item.satisfactionId">
            </el-option>
          </el-select>
        </div>
        <div class="mar-t-8">
         <span class="color-primary cur-point" @click="openSetReviewQuestion">{{ $t('task.setting.taskTypeSetting.flow.components.goToSetReviewScheme') }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/* api */
import { getProjectAutoReview, updateProjectAutoReview, getProjectTypeField } from '@src/api/ProjectManage.ts';
import { getUsedConfigList } from "@src/api/SettingApi";
/* utils*/
import { isEmpty } from 'pub-bbx-utils'
import { openAccurateTab } from "@src/util/platform";
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

export default {
  name: "SatisfiedReviewSetting",
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
  },
  data() {
    return {
      loading: false,
      autoReviewState: false, // 是否开启满意度回访开关

      reviewType: 'customer', // 选择的类型
      reviewPhoneFieldName: '', // 选择的电话控件字段
      phoneFields: [], // 项目表单中电话的字段

      questionId: '', // 设置的回访方案
      allQuestions: [], // 所有的问卷方案
    }
  },
  methods: {
    /*更新满意度设置*/
    async updateReviewSetting() {
      if(this.reviewType === 'otherPhone' && isEmpty(this.reviewPhoneFieldName)) {
        this.reviewPhoneFieldName = this.phoneFields?.[0]?.fieldName ?? ''
      }

      try {
        const params = {
          config: {
            autoReviewState: this.autoReviewState,
            questionId: this.questionId,
            reviewFieldName: this.reviewType === 'customer' ? this.reviewType : this.reviewPhoneFieldName,
          },
          templateId: this.templateId
        }

        const { success = false, message = ''} = await updateProjectAutoReview(params)

        this.$message({
          type: success ? 'success' : 'error',
          message: success ? this.$t('common.base.tip.updateSuccess') : message
        })
      } catch (e) {
        console.error(e)
      }
    },

    /*跳转满意度列表*/
    openSetReviewQuestion() {
      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerExperienceQuestionnaireSchemeList,
        reload: true,
        fromId
      })
    },

    /*获取满意度配置信息*/
    async fetchProjectAutoReview() {
      try {
        const { success, message, data = {} } = await getProjectAutoReview({ templateId: this.templateId })

        if(!success) this.$message.error(message)

        const {
          autoReviewState = false,
          questionId = '',
          reviewFieldName = '',
        } = data

        this.autoReviewState = autoReviewState;
        this.questionId = questionId;

        if(reviewFieldName === 'customer' || isEmpty(reviewFieldName) || !this.phoneFields?.length) {
          this.reviewType = 'customer'
        }else {
          // 如果选择的电话字段被删除，需要默认置空
          if(this.phoneFields?.every(item => item.fieldName !== reviewFieldName)) {
            this.reviewPhoneFieldName = ''
          }else {
            this.reviewPhoneFieldName = reviewFieldName
          }
          this.reviewType = 'otherPhone'
        }
      } catch (e) {
        console.error(e)
      }
    },

    /*查询表单字段*/
    async getProjectTypeField() {
      try {
        const { success, data } = await getProjectTypeField({
          templateId: this.templateId,
          tableName: 'project'
        })

        if(success) {
          this.phoneFields = data?.filter(item => item.formType === 'phone' && item.isHidden != 1)?.map(item => {
            return {
              displayName: item.displayName,
              fieldName: item.fieldName
            }
          })
        }
      } catch (e) {
        console.error(e)
      }
    },

    /** 初始化满意度方案*/
    async initEvaluationOptions() {
      try {
        // 满意度方案初始化
        let { success = false, result = []} = await getUsedConfigList({});

        success && (this.allQuestions = result);

      } catch (error) {
        console.error('fetch getUsedConfigList => err', error);
      }
    },
    async initReviewSetting() {
      try {
        this.loading = true;
        await this.getProjectTypeField();
        await this.initEvaluationOptions();
        await this.fetchProjectAutoReview();
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false;
      }
    },
  },
  mounted() {
    this.initReviewSetting();
  },
}
</script>

<style lang="scss" scoped>
.satisified-review {
  padding: 24px;

  &-open {
    display: flex;
    justify-content: space-between;
  }

  &-item {
    margin-bottom: 24px;

    .title {
      position: relative;
      font-size: 14px;
      color: #333;
      margin-bottom: 4px;

      &::before {
        background: $color-primary-light-6;
        border-radius: 2px;
        content: '';
        display: inline-block;
        height: 14px;
        left: -8px;
        position: absolute;
        top: 2px;
        width: 2px;
      }
    }
    .tip {
      font-size: 12px;
      color: #999;
    }

    &:last-child {
      margin-bottom: 0;
    }

    .review-content {
      display: flex;

      .phone-field {
        margin-top: 4px;
        display: flex;
        align-items: center;
        height: 32px;
      }
    }

    &-type {
      display: flex;
      flex-direction: column;
      margin-top: 8px;

      .el-select {
        margin-left: 8px;
      }
    }

    .programme {
      display: flex;
      align-items: center;

      .el-select {
        margin-left: 8px;
      }
    }
  }
}
</style>